﻿/*
The MIT License (MIT)
Copyright (c) 2013 kaveh.shahbazian@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), 
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
IN THE SOFTWARE.
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Buddy
{
    /// <summary>
    /// an implementation of channels in Go
    /// used:
    /// https://github.com/mono/mono/blob/master/mcs/class/corlib/System.Collections.Concurrent/ConcurrentQueue.cs
    /// </summary>
    /// <typeparam name="TPayload"></typeparam>
    public class Channel<TPayload>
    {
        class Node
        {
            public TPayload Value;
            public Node Next;
        }

        Node _head = new Node();
        Node _tail;
        long _count;

        readonly long _size;
        readonly Semaphore _semHead = new Semaphore(1, 1);
        readonly ManualResetEvent _closed = new ManualResetEvent(false);

        public Channel(long size)
        {
            if (size < 1) size = 1;

            _size = size;
            _count = 0;
            _tail = _head;
        }
        public Channel() : this(1) { }

        public bool Send(TPayload val)
        {
            if (IsClosed) return false;

            if (Interlocked.Read(ref _count) >= _size)
            {
                var e = WaitHandle.WaitAny(new WaitHandle[] { _closed, _semHead });
                if (e == 0) return false;

                if (Interlocked.Read(ref _count) >= _size) SpinWait.SpinUntil(() => IsClosed || (Interlocked.Read(ref _count) < _size));

                if (IsClosed) return false;

                SendH(val);

                _semHead.Release();
            }
            else { SendH(val); }

            return true;
        }

        void SendH(TPayload val)
        {
            Node node = new Node();
            node.Value = val;

            Node oldTail = null;
            Node oldNext = null;

            bool update = false;
            while (!update)
            {
                oldTail = _tail;
                oldNext = oldTail.Next;

                // Did tail was already updated ?
                if (_tail == oldTail)
                {
                    if (oldNext == null)
                    {
                        // The place is for us
                        update = Interlocked.CompareExchange(ref _tail.Next, node, null) == null;
                    }
                    else
                    {
                        // another Thread already used the place so give him a hand by putting tail where it should be
                        Interlocked.CompareExchange(ref _tail, oldNext, oldTail);
                    }
                }
            }
            // At this point we added correctly our node, now we have to update tail. If it fails then it will be done by another thread
            Interlocked.CompareExchange(ref _tail, node, oldTail);
            Interlocked.Increment(ref _count);
        }

        public bool Receive(out TPayload val)
        {
            val = default(TPayload);

            if (IsClosed) return false;

            while (!IsClosed && !RcvdH(out val)) if (Interlocked.Read(ref _count) == 0) SpinWait.SpinUntil(() => IsClosed || Interlocked.Read(ref _count) > 0);

            if (IsClosed) return false;

            return true;
        }

        bool RcvdH(out TPayload val)
        {
            val = default(TPayload);

            bool advanced = false;

            while (!advanced)
            {
                Node oldHead = _head;
                Node oldTail = _tail;
                Node oldNext = oldHead.Next;

                if (oldHead == _head)
                {
                    // Empty case ?
                    if (oldHead == oldTail)
                    {
                        // This should be false then
                        if (oldNext != null)
                        {
                            // If not then the linked list is mal formed, update tail
                            Interlocked.CompareExchange(ref _tail, oldNext, oldTail);
                            continue;
                        }

                        val = default(TPayload);
                        return false;
                    }
                    else
                    {
                        val = oldNext.Value;
                        advanced = Interlocked.CompareExchange(ref _head, oldNext, oldHead) == oldHead;
                    }
                }
            }

            Interlocked.Decrement(ref _count);

            return true;
        }

        public void Close()
        {
            _closed.Set();
            IsClosed = true;
        }

        bool IsClosed { get; set; }
    }
}
